/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import Fachada.Fachada;
import classes.Unidade;
import erro.ConexaoException;
import erro.ConsultaException;
import erro.DaoException;
import erro.GeralException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Igor
 */
public class telaPesquisarUnidade extends javax.swing.JFrame {

    private static Fachada f;

    /**
     * Creates new form telaPesquisarUnidade
     */
    public telaPesquisarUnidade() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        ButtonAltUni = new javax.swing.JButton();
        txtBoxPesqNomeUni = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        TableUnidade = new javax.swing.JTable();
        ButtonCancelar = new javax.swing.JButton();
        jButtonListarTabela = new javax.swing.JButton();
        jButtonPesquUni = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Nome:");

        ButtonAltUni.setText("ALTERAR");
        ButtonAltUni.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonAltUniActionPerformed(evt);
            }
        });

        TableUnidade.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null},
                {null},
                {null},
                {null}
            },
            new String [] {
                "Nome"
            }
        ));
        TableUnidade.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableUnidadeMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(TableUnidade);

        ButtonCancelar.setText("CANCELAR");
        ButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonCancelarActionPerformed(evt);
            }
        });

        jButtonListarTabela.setText("LISTAR");
        jButtonListarTabela.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonListarTabelaActionPerformed(evt);
            }
        });

        jButtonPesquUni.setText("PESQUISAR");
        jButtonPesquUni.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPesquUniActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 36));
        jLabel2.setText("Pesquisar Unidade");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtBoxPesqNomeUni, javax.swing.GroupLayout.PREFERRED_SIZE, 224, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(24, 24, 24)
                                .addComponent(jButtonPesquUni, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(26, 26, 26)
                                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(46, 46, 46)
                                .addComponent(ButtonAltUni, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButtonListarTabela, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(ButtonCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(69, 69, 69)
                        .addComponent(jLabel2)))
                .addGap(29, 29, 29))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jButtonPesquUni, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtBoxPesqNomeUni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ButtonAltUni, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ButtonCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
                    .addComponent(jButtonListarTabela, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ButtonAltUniActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonAltUniActionPerformed
        telaAlterarUnidade alterauni = new telaAlterarUnidade();
        alterauni.setVisible(true);
        Unidade uni = new Unidade();
        f = Fachada.getInstancia();
        uni.setNomeUnidade(txtBoxPesqNomeUni.getText());
        try {
            f.pesquisarUnid(uni);
        } catch (DaoException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (GeralException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        if ((uni.getCodUnidade() == null)){
            alterauni.setVisible(false);
            alterauni.dispose();
        } else {
            
            alterauni.LabelCodUni.setText(Integer.toString(uni.getCodUnidade()));
            alterauni.txtBoxNomeUni.setText(uni.getNomeUnidade());
        }
    }//GEN-LAST:event_ButtonAltUniActionPerformed

    private void TableUnidadeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TableUnidadeMouseClicked
        int x = TableUnidade.getSelectedRow();
        int y = TableUnidade.getSelectedColumn();

        //Se o clique for duplo
        if (evt.getClickCount() == 1) {
            if (evt.getButton() == evt.BUTTON1) {//E o botão for o esquerdo

                txtBoxPesqNomeUni.setText((String) TableUnidade.getValueAt(x, 0));
            }
        }
    }//GEN-LAST:event_TableUnidadeMouseClicked

    private void ButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonCancelarActionPerformed
        telaPesquisarUnidade tlpesquni = new telaPesquisarUnidade();
        int i = JOptionPane.showConfirmDialog(null, "Deseja realmente Cancelar?", "Cancelar", JOptionPane.YES_NO_OPTION);
        if (i == JOptionPane.YES_OPTION) {
            telaPesquisarUnidade.this.setVisible(false);
            tlpesquni.dispose();
        } else {
            repaint();
        }
    }//GEN-LAST:event_ButtonCancelarActionPerformed

    private void jButtonListarTabelaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonListarTabelaActionPerformed
        listarTabela();
        txtBoxPesqNomeUni.setText("");
    }//GEN-LAST:event_jButtonListarTabelaActionPerformed

    private void jButtonPesquUniActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPesquUniActionPerformed
        TableUnidade.getColumnModel().getColumn(0).setPreferredWidth(150);
        DefaultTableModel modelo = (DefaultTableModel) TableUnidade.getModel();
        modelo.setNumRows(0);
        f = Fachada.getInstancia();
        Unidade uni = new Unidade();
        ArrayList<Unidade> lista = new ArrayList<Unidade>();
        try {
            uni.setNomeUnidade(txtBoxPesqNomeUni.getText()+"%");
            lista = (ArrayList<Unidade>) f.pesquisarUni(uni);
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        for (int i = 0; i < lista.size(); i++) {
            modelo.addRow(new Object[]{lista.get(i).getNomeUnidade(),});
        }
        TableUnidade.setModel(modelo);
    }//GEN-LAST:event_jButtonPesquUniActionPerformed
    
    public void listarTabela() {
        TableUnidade.getColumnModel().getColumn(0).setPreferredWidth(150);
        DefaultTableModel modelo = (DefaultTableModel) TableUnidade.getModel();
        modelo.setNumRows(0);
        f = Fachada.getInstancia();
        Unidade uni = new Unidade();
        ArrayList<Unidade> lista = new ArrayList<Unidade>();
        try {
            lista = (ArrayList<Unidade>) f.listar(uni);
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
        for (int i = 0; i < lista.size(); i++) {
            modelo.addRow(new Object[]{lista.get(i).getNomeUnidade(),});
        }
        TableUnidade.setModel(modelo);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarUnidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarUnidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarUnidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(telaPesquisarUnidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new telaPesquisarUnidade().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonAltUni;
    private javax.swing.JButton ButtonCancelar;
    private javax.swing.JTable TableUnidade;
    private javax.swing.JButton jButtonListarTabela;
    private javax.swing.JButton jButtonPesquUni;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField txtBoxPesqNomeUni;
    // End of variables declaration//GEN-END:variables
}
